package com.qiniu.githubdata.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
class ProxyInfo {
    final String ip;
    final int port;

    ProxyInfo(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }
}
public class ProxyUtil {
    final static String secretId = "ozfhzt26h5xb30xo53zu";
    final static String signature = "jzkgoem6d6n1wforv2yxrdcbj9dcz3nw";
    final static String urlString = "https://dps.kdlapi.com/api/getdps/?secret_id=" + secretId + "&signature=" + signature + "&num=1&pt=1&format=text&sep=1,";

    // 用户名密码认证(私密代理/独享代理)
    final static String ProxyUser = "d1112721220";
    final static String ProxyPass = "gxj3gnzm";
    // 添加静态初始化块
    static {
        // 设置 HTTPS 认证
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
        // 设置代理认证
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(ProxyUser, ProxyPass.toCharArray());
            }
        });
    }

    public static Document fetchGithubContent(String targetUrl) throws IOException {
        ProxyInfo proxyInfo = IpPool.getProxy();
        Document dic= fetchGithubContent(targetUrl, proxyInfo);
        IpPool.releaseProxy(proxyInfo);
        return dic;
    }

        public static Document fetchGithubContent(String targetUrl,  ProxyInfo proxyInfo) {
        int maxRetries = 3;
        int attempt = 0;
        boolean success = false;
//            System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        while (attempt < maxRetries ) {
            try {
                // Enable HTTPS proxy authentication

                // Get proxy details
//                ProxyInfo proxyInfo = IpPool.getProxy();
                if (proxyInfo != null) {
                    System.out.println("Using proxy: " + proxyInfo.ip + ":" + proxyInfo.port);
                    Document document = fetchContentThroughProxy(targetUrl, proxyInfo.ip, proxyInfo.port);
                    success = true;
//                    System.out.println(document.body().html());
                    return document;
                }
            } catch (IOException e) {
                attempt++;
                System.err.println("Failed to fetch content (attempt " + attempt + "): " + e.getMessage());
                if (attempt >= maxRetries) {
                    e.printStackTrace();
                }
                // Wait before retrying
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
        return null;
    }
    public static ProxyInfo getProxyInfo() throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String response = reader.readLine();
            if (response != null) {
                String[] parts = response.split(":");
                if (parts.length >= 2) {
                    return new ProxyInfo(parts[0].trim(), Integer.parseInt(parts[1].trim()));
                }
            }
        } finally {
            connection.disconnect();
        }
        return null;
    }
    
    public static Document fetchContentThroughProxy(String targetUrl, String ip, int port) throws IOException {
        // Set up proxy authentication
//        Authenticator.setDefault(new Authenticator() {
//            @Override
//            protected PasswordAuthentication getPasswordAuthentication() {
//                return new PasswordAuthentication(ProxyUser, ProxyPass.toCharArray());
//            }
//        });
        
        // Create proxy
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));
        
        // Fetch content
        Document doc = Jsoup.connect(targetUrl)
                .followRedirects(false)
                .timeout(6000)
                .proxy(proxy)
                .get();
                
//        if (doc != null) {
//            System.out.println(doc.body().html());
//        }
        return doc;
    }
    

    
    // Example usage
    public static void main(String[] args) {
        try {
//            ProxyInfo proxyInfo = getProxyInfo();
//            fetchGithubContent("https://github.com", proxyInfo);
            fetchGithubContent("https://github.com/");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}